import { createRouter, createWebHashHistory } from "vue-router";
import Home from "@/views/Home/index.vue";
import Login from "@/views/Login/index.vue";
import { getCode } from "@/api/login";
import { ElMessage } from 'element-plus'
// import Register from "@/views/Register/index.vue";
// 创建路由

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      name: "Home",
      component: Home,
      meta: {
        title: "收藏",
      },
    },
    {
      path: "/message",
      name: "message",
      component: () => import("@/views/Message/index.vue"),
      meta: {
        title: "聊天",
      },
    },
    {
      path: "/shop",
      name: "shop",
      component: () => import("@/views/Shop/index.vue"),
      meta: {
        title: "电商",
      },
    },
    {
      path: "/background",
      name: "background",
      component: () => import("@/views/Background/index.vue"),
      meta: {
        title: "背景图",
      },
    },
    {
      path: "/map",
      name: "map",
      component: () => import("@/views/map/index.vue"),
      meta: {
        title: "地图",
      },
    },
    {
      path: "/login",
      name: "Login",
      components: { login: Login },
    },
  ],
})

var loginstate = false
router.beforeEach(async (to, from, next) => {
  // console.log(to,from,next);
  const token = localStorage.getItem("token")
  if (token) {
    if (!loginstate) {
      loginstate = true
      let res = await getCode()
      if (res.code == 0) {
        loginstate = false
        localStorage.removeItem("token")
        localStorage.removeItem("user")
        ElMessage.error("登录过期，请重新登录")
        next("/login")
        return
      }
    }
    if (to.path == "/login") {
      next(from.path)
    } else {
      next()
    }
  } else {
    if (to.path == "/login") {
      next()
    } else {
      next("/login")
    }
  }
}
)
export default router